import grails.test.*

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.TEXT
import static groovyx.net.http.ContentType.HTML

class ReplyTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    // 기사 베플 파싱 
    void testParsingBestReplies() {
    	String articleUrl = 'http://news.nate.com/view/20100104n13283'
		def url = new URL(articleUrl)
		println url
		def articleId = url.getPath().replace('/view/', '')
		
    	def htmlComment = new HTTPBuilder('http://newscomm.nate.com').request(GET,TEXT) { 
    		uri.path = '/ArticleComment/List'
			uri.query = [ artc_sq: articleId, ]
		}
        assert htmlComment instanceof Reader // response data is buffered in-memory
        def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
        
    	def html = slurper.parse(htmlComment)
		def beple = html.'**'.find{ it.name() == 'div' && it.@class == 'cmt_best' }.dl
		def listOfBeple = []
		
		for( reply in beple.list() ) {
			// 네이트의 댓글 작성자 이름(username)은 
			// 싸이월드 링크가 있을 때와 없을 때가 태그 구성 모습 다르기 때문에
			// 두 가지 방법으로 모두 접근해 줘야 할 필요가 있다.
			String username 
			try {
				username = reply.'**'.find{ it.name() == 'a' && it.@class == 'nameui' }.text().trim()
			} catch(NullPointerException e) {
				username = reply.'**'.find{ it.name() == 'dt' && it.@class == 'beple' }.text().trim()
			}
			Date dateCreated = Date.parse('(MM.dd hh:mm)', reply.'**'.find{ it.name() == 'dd' && it.@class == 'usertxt' }.i.text())
			reply.'**'.find{ it.name() == 'dd' && it.@class == 'usertxt' }.i.replaceBody('')
			String content = reply.'**'.find{ it.name() == 'dd' && it.@class == 'usertxt' }.text().trim()
			int countOfGood = reply.'**'.find{ it.name() == 'dd' && it.@class == 'n_good' }.text().trim() as int
			int countOfBad = reply.'**'.find{ it.name() == 'dd' && it.@class == 'n_bad' }.text().trim() as int
			
			listOfBeple.add( [username:username, dateCreated:dateCreated, content:content, countOfGood:countOfGood, countOfBad:countOfBad, ] )
		}
		
		println listOfBeple
    }
    
    void testReplyClass() {
    	// 베플 파싱
		String articleUrl = 'http://news.nate.com/view/20100104n13283'
		def listOfBeple = Reply.parseBestReplies(articleUrl)

		for(beple in listOfBeple) {
			println "$beple.username, $beple.content, $beple.dateCreated"
		}
    }
}
